package black.market.weather;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import black.market.util.Log;

public class WeatherContentProvider extends ContentProvider {
	private static final String LOGTAG = "WeatherContentProvider";

	public static final int DBVER = 1;
	public static final String DATABASE_NAME = "example_weather.db";
	public static final String WB_ID = "wb_id"; // 테이블 유니크 SEQ ID
	public static final String WB_HEADER_ID = "wb_header_id"; // 테이블 유니크 SEQ ID
	public static final String WB_BODY_ID = "wb_body_id"; // 테이블 유니크 SEQ ID
	public static final String WB_TABLE = "wb_table"; // 테이블 이름
	public static final String WB_HEADER_TABLE = "wb_header_table"; // 테이블 이름
	public static final String WB_BODY_TABLE = "wb_body_table"; // 테이블 이름
	public static final String WB_TIMEMAP = "wb_timemap"; // 발표시각
	public static final String WB_TIMESTEP = "wb_timestep"; // 발표단계 :
															// 1.오늘오후/2.내일오전/3.내일오후/4.모레오전
	public static final String WB_LATITUDE = "wb_latitude";
	public static final String WB_LONGITUDE = "wb_longitude";
	public static final String WB_SEQ = "wb_seq";
	public static final String WB_HOUR = "wb_hour"; // 동네예보 3시간단위 시간(1시간: 기온,
													// 풍향,
													// 풍속, 습도), (3시간: 하늘상태,
													// 강수상태, 강수확률)
	public static final String WB_DAY = "wb_day"; // (1:오늘, 2:내일, 3:모레)
	public static final String WB_TEMP = "wb_temp"; // 현재시간온도(3시간 단위)
	public static final String WB_TEMPMAX = "wb_tempmax"; // 최고온도(missing:값이 없을
															// 경우)
	public static final String WB_TEMPMIN = "wb_tempmin"; // 최저온도(missing:값이 없을
															// 경우)
	public static final String WB_SKY = "wb_sky"; // 하늘상태(1:맑음, 2:구름조금, 3:구름많음,
													// 4:흐림
	public static final String WB_PRECIPITATION = "wb_precipitation"; // 날씨상태(0:없음,
																		// 1:비,
																		// 2:비/눈,
																		// 3:눈/비,
																		// 4:눈
	public static final String WB_KOR_STATE = "wb_kor_state"; // 1.맑음_2.구름조금_3.구름많음_4.흐림_5.비_6.눈/비_7.눈
	public static final String WB_EN_STATE = "wb_en_state"; // 1.맑음_2.구름조금_3.구름많음_4.흐림_5.비_6.눈/비_7.눈
	public static final String WB_POP = "wb_pop"; // 강수확률
	public static final String WB_RAIN12 = "wb_rain12"; // 예상 강수량
	public static final String WB_SNOW12 = "wb_snow12"; // 예상 적설량
	public static final String WB_WINDSPEED = "wb_windspeed"; // 풍속
	public static final String WB_WINDDIRECTION = "wb_wind_direction";// 풍향=0~7(북_북동_동_남동_남_남서_서_북서)
	public static final String WB_EN_WINDDIRECTION = "wb_en_wind_direction";// 풍향=0~7(북_북동_동_남동_남_남서_서_북서)
	public static final String WB_KOR_WINDDIRECTION = "wb_kor_direction";// 풍향=0~7(북_북동_동_남동_남_남서_서_북서)
	public static final String WB_REH = "wb_reh"; // 습도
	public static final String WB_DATATYPE = "wb_datatype"; // 날씨 정보 제공처

	private static final int HEADER_ALLCURSOR = 5;
	private static final int HEADER_ONECURSOR = 6;
	private static final int BODY_ALLCURSOR = 7;
	private static final int BODY_ONECURSOR = 8;
	private SQLiteDatabase database = null;
	public static final Uri HEADER_URI = Uri.parse("content://black.market.weather.WeatherContentProvider/header");
	public static final Uri BODY_URI = Uri.parse("content://black.market.weather.WeatherContentProvider/body");
	static final UriMatcher MATCHER;
	static {
		MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
		MATCHER.addURI("black.market.weather.WeatherContentProvider", "header", HEADER_ALLCURSOR);
		MATCHER.addURI("black.market.weather.WeatherContentProvider", "header/*", HEADER_ONECURSOR);
		MATCHER.addURI("black.market.weather.WeatherContentProvider", "body", BODY_ALLCURSOR);
		MATCHER.addURI("black.market.weather.WeatherContentProvider", "body/*", BODY_ONECURSOR);
	}

	private static final String HEADER_CREATE = "CREATE TABLE " + WB_HEADER_TABLE + " (" + WB_HEADER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + WB_TIMEMAP + " STRING," + WB_TIMESTEP + " STRING,"
			+ WB_LATITUDE + " STRING," + WB_LONGITUDE + " STRING" + ")";

	private static final String BODY_CREATE = "CREATE TABLE " + WB_BODY_TABLE + " (" + WB_BODY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + WB_TIMEMAP + " STRING," + WB_SEQ + " STRING," + WB_HOUR
			+ " STRING," + WB_DAY + " STRING," + WB_TEMP + " STRING," + WB_TEMPMAX + " STRING," + WB_TEMPMIN + " STRING," + WB_SKY + " STRING," + WB_PRECIPITATION + " STRING," + WB_EN_STATE
			+ " STRING," + WB_KOR_STATE + " STRING," + WB_POP + " STRING," + WB_RAIN12 + " STRING," + WB_SNOW12 + " STRING," + WB_WINDSPEED + " STRING," + WB_WINDDIRECTION + " STRING,"
			+ WB_KOR_WINDDIRECTION + " STRING," + WB_EN_WINDDIRECTION + " STRING," + WB_REH + " STRING" + WB_DATATYPE + " STRING" + ")";

	@Override
	public boolean onCreate() {
		// TODO Auto-generated method stub
		WeatherDBHelper dbHelper = new WeatherDBHelper(getContext(), DATABASE_NAME, null, DBVER);
		database = dbHelper.getWritableDatabase();
		return (database == null) ? false : true;
	}

	@Override
	public String getType(Uri uri) {
		// TODO Auto-generated method stub
		switch (MATCHER.match(uri)) {
		case HEADER_ALLCURSOR:
			return "vnd.black.market.weather.WeatherContentProvider.dir//header";
		case HEADER_ONECURSOR:
			return "vnd.black.market.weather.WeatherContentProvider.item//header";
		case BODY_ALLCURSOR:
			return "vnd.black.market.weather.WeatherContentProvider.dir//body";
		case BODY_ONECURSOR:
			return "vnd.black.market.weather.WeatherContentProvider.item//body";
		default:
			throw new IllegalArgumentException(LOGTAG + " Unsupport URI: " + uri);
		}
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		// TODO Auto-generated method stub
		Uri tmpUri = null;
		switch (MATCHER.match(uri)) {
		case HEADER_ALLCURSOR:
			long headerId = database.insert(WB_HEADER_TABLE, "", values);
			Log.d(LOGTAG, "Insert Count: " + headerId);
			if (headerId > 0) {
				tmpUri = ContentUris.withAppendedId(HEADER_URI, headerId);
				getContext().getContentResolver().notifyChange(tmpUri, null);
			} else {
				try {
					throw new SQLException("Fail to add new item into " + uri);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			break;

		case BODY_ALLCURSOR:
			long bodyId = database.insert(WB_BODY_TABLE, "", values);
			Log.d(LOGTAG, "Insert Count: " + bodyId);
			if (bodyId > 0) {
				tmpUri = ContentUris.withAppendedId(BODY_URI, bodyId);
				getContext().getContentResolver().notifyChange(tmpUri, null);
			} else {
				try {
					throw new SQLException("Fail to add new item into " + uri);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			break;

		default:
			try {
				throw new IllegalAccessException("Unsupport URI: " + uri);
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		}
		return tmpUri;
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		// TODO Auto-generated method stub
		int count = 0;
		switch (MATCHER.match(uri)) {
		case HEADER_ALLCURSOR:
			count = database.delete(WB_HEADER_TABLE, selection, selectionArgs);
			break;
		case HEADER_ONECURSOR:
			count = database.delete(WB_HEADER_TABLE, selection, selectionArgs);
			break;
		case BODY_ALLCURSOR:
			count = database.delete(WB_BODY_TABLE, selection, selectionArgs);
			break;
		case BODY_ONECURSOR:
			count = database.delete(WB_BODY_TABLE, selection, selectionArgs);
			break;

		default:
			throw new IllegalArgumentException("Unsupport URI:" + uri);
		}
		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
		// TODO Auto-generated method stub
		int count = 0;
		switch (MATCHER.match(uri)) {
		case HEADER_ALLCURSOR:
			count = database.update(WB_HEADER_TABLE, values, selection, selectionArgs);
			break;
		case HEADER_ONECURSOR:
			count = database.update(WB_HEADER_TABLE, values, selection, selectionArgs);
			break;
		case BODY_ALLCURSOR:
			count = database.update(WB_BODY_TABLE, values, selection, selectionArgs);
			break;
		case BODY_ONECURSOR:
			count = database.update(WB_BODY_TABLE, values, selection, selectionArgs);
			break;

		default:
			try {
				throw new IllegalAccessException("Unsupport URI: " + uri);
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		}
		return count;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
		// TODO Auto-generated method stub
		SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
		switch (MATCHER.match(uri)) {
		case HEADER_ALLCURSOR:
			builder.setTables(WB_HEADER_TABLE);
			break;
		case HEADER_ONECURSOR:
			builder.setTables(WB_HEADER_TABLE);
			break;
		case BODY_ALLCURSOR:
			builder.setTables(WB_BODY_TABLE);
			break;
		case BODY_ONECURSOR:
			builder.setTables(WB_BODY_TABLE);
			break;
		default:
			try {
				throw new IllegalAccessException("Unsupport URI: " + uri);
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		}
		Cursor cursor = builder.query(database, projection, selection, selectionArgs, null, null, sortOrder);
		cursor.setNotificationUri(getContext().getContentResolver(), uri);
		return cursor;
	}

	public static class WeatherDBHelper extends SQLiteOpenHelper {
		private static final String LOGTAG = "WeatherDBHelper";

		public WeatherDBHelper(Context context, String name, CursorFactory factory, int version) {
			super(context, name, factory, version);
			// TODO Auto-generated constructor stub
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			// TODO Auto-generated method stub
			Log.d(LOGTAG, "Create Header table");
			db.execSQL(HEADER_CREATE);
			Log.d(LOGTAG, "Create Body table");
			db.execSQL(BODY_CREATE);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			// TODO Auto-generated method stub
			Log.d(LOGTAG, "Drop Header table");
			db.execSQL("DROP TABLE IF EXISTS " + WB_HEADER_TABLE);
			Log.d(LOGTAG, "Drop Body table");
			db.execSQL("DROP TABLE IF EXISTS " + WB_BODY_TABLE);
			onCreate(db);
		}

		@Override
		public synchronized void close() {
			// TODO Auto-generated method stub
			super.close();
		}
	}

}
